package com.ihr360.payroll.controller.heath;

import com.ihr360.admin.client.controller.health.vo.ServiceHealth;
import com.ihr360.admin.client.controller.health.vo.ServiceStatus;
import com.ihr360.admin.client.scheduled.AdminClientHealthCheck;
import com.ihr360.payroll.dao.ReferenceApplicationRepository;
import com.ihr360.payroll.model.dto.reference.ReferenceApplication;
import com.ihr360.shared.advice.response.DisableResponseAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Iterator;
import java.util.List;

@RestController
@RequestMapping({"/health"})
public class CustomizeHealthCheckController {
    @Autowired
    private ReferenceApplicationRepository referenceApplicationRepository;

    @Autowired
    private AdminClientHealthCheck adminClientHealthCheck;

    @Autowired
    private RestTemplate restTemplate = new RestTemplate();

    @Value("${spring.application.name:default}")
    protected String localServiceId;

    @Value("${ihr360.config.brand:default}")
    protected String brand;

    @RequestMapping("/check")
    @DisableResponseAdvice
    public ServiceHealth check() {
        ServiceHealth health = adminClientHealthCheck.check();
        Iterable<ReferenceApplication> applications = referenceApplicationRepository.findAll();
        Iterator<ReferenceApplication> iterator = applications.iterator();
        List<ServiceHealth> serviceHealths = health.getCallings();
        serviceHealths = health.getCallings();
        if (iterator.hasNext()) {
            ReferenceApplication application = iterator.next();
            String baseUrl = application.getBaseUrl();
            try {
                ServiceHealth e = restTemplate.getForObject(baseUrl+"/health/check", ServiceHealth.class);
                serviceHealths.add(e);
            } catch (Exception e) {
                serviceHealths.add(new ServiceHealth(application.getRefId(), this.brand, baseUrl, ServiceStatus.ERROR, e.getMessage()));
            }
        }
        return health;
    }
}